<?php
/**
 * This file is part of webmanCMS.
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the MIT-LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @author    王旋 <2073864115@qq.com>
 * @copyright 王旋 <2073864115@qq.com>
 * @license   http://www.opensource.org/licenses/mit-license.php MIT License
 */
namespace app\middleware;

use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;

class Cors implements MiddlewareInterface
{
    protected array $header = [
        'Access-Control-Allow-Credentials' => 'true',
        'Access-Control-Max-Age'           => 1800,
        'Access-Control-Allow-Methods'     => 'GET, POST, PATCH, PUT, DELETE, OPTIONS',
        'Access-Control-Allow-Headers'     => 'Authorization, Content-Type, X-Requested-With, token, app-token',
    ];
    public function process(Request $request, callable $handler): Response
    {
        if ($request->method() == 'OPTIONS') {
            $response = response();
        } else {
            $response = $handler($request);
        }

        if (!$response->getHeader('Access-Control-Allow-Origin')) {
            $header = $this->header;
            $header['Access-Control-Allow-Origin'] = '*';
            $response->withHeaders($header);
        }
        return $response;
    }
}